<template>
  <div class="app-container">
    <!--    <el-row :gutter="20">-->
    <!-- 设备列表 -->
    <!--      <el-col :lg="24" :xs="24">-->
    <div class="toolbar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="title">
          <el-input
            v-model="queryParams.title"
            placeholder="新闻标题"
            clearable
            style="width: 300px;height: 30px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size='large' @click="handleQuery" :icon='Search'
          >搜索</el-button
          >
          <el-button @click="resetQuery" size='large' :icon='Refresh'>
            重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="toolbar" style='margin-bottom: 10px;'>
      <div>
        <el-button
          size='large'
          type="primary"
          :icon='Plus'
          @click="openDialog('user-form')"
        >新增</el-button
        >
      </div>
    </div>
    <el-table
      v-loading="loading"
      :data="pageData"
      :strip='true'
      :border='true'
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column
        key="id"
        label="新闻id"
        align="center"
        prop="id"
        width="100"
      />
      <el-table-column
        key="title"
        label="新闻标题"
        align="center"
        prop="title"
        width="200"
      />
<!--      <el-table-column
        label="新闻内容"
        width="200"
        align="center"
        prop="content"
      />-->
      <el-table-column
        label="图片"
        align="center"
        prop="pic"
      >
        <template #default="scope">
          <div style="width: 100px;height: 100px;margin: 0 auto">
            <img style="width: 100%;height: 100%;object-fit: cover" :src="scope.row.pic" :alt="scope.row.name" />
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      />
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        width="180"
      />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
            type="success"
            size="large"
            @click="openDialog('user-form', scope.row.id)"
            :icon="Edit"
          >编辑</el-button
          >
          <el-button
            type="warning"
            size="large"
            @click="handleDeleteEquipment(scope.row.id)"
            :icon="Delete"
          >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-footer class='footer'>
      <el-pagination
        large
        background
        v-model:current-page="pagination.pageNum"
        v-model:page-size="pagination.pageSize"
        :page-count='pagination.pageCount'
        layout='total, prev, pager, next'
        :total='pagination.total'
        class='mt-4'
        style='float: right'
        @change='getPage'
      />
    </el-footer>
    <!--        </el-card>-->
    <!--      </el-col>-->
    <!--    </el-row>-->

    <!-- 弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      append-to-body
      @close="closeDialog"
      :fullscreen="true"
    >
      <!-- 用户新增/编辑表单 -->
      <el-form
        v-if="dialog.type === 'user-form'"
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="新闻标题" prop="title">
          <el-input
            v-model="formData.title"
            placeholder="请输入新闻标题"
          />
        </el-form-item>

        <el-form-item label="图片" prop="pic">
          <el-upload ref='upload' :before-upload='beforeAvatarUpload'  :on-success='handleSuccess' v-model:file-list="uploadFiles"
                     :action="action" list-type="picture-card" :auto-upload="true" :limit='1' :on-exceed='handleExceed'>
            <el-icon><Plus /></el-icon>

            <template #file="{ file }">
              <div>
                <img class="el-upload-list__item-thumbnail" :src="imgUrl"  style='height: 100%;' alt="" />
                <span class="el-upload-list__item-actions">
          <span
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(file)"
          >
            <el-icon><zoom-in /></el-icon>
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleRemove(file)"
          >
            <el-icon><Delete /></el-icon>
          </span>
        </span>
              </div>
            </template>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>
<!--        <el-form-item label="设备价格" prop="price">
          <el-input v-model="formData.price" placeholder="请输入设备价格，单位为分" />
        </el-form-item>-->

        <el-form-item label="内容" prop="content">
          <div style='min-height: 500px;width:80%;'>
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
            />
            <Editor
              style="height: auto"
              v-model="formData.content"
              :defaultConfig="editorConfig"
              @onCreated="handleCreated"
            />
          </div>

        </el-form-item>
      </el-form>

      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang='ts'>
import { Plus, Delete, Edit, Search, Share, Refresh, ZoomIn } from '@element-plus/icons-vue'
import {
  type UploadInstance,
  ElMessageBox,
  ElMessage,
  ElForm,
  type UploadProps,
  type UploadRawFile
} from 'element-plus'
import { ref, onMounted, reactive, shallowRef } from 'vue'
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { getNewsForm, getNewsPage,addNews, updateNews, deleteNews } from '@/api/sys/news.ts'
import { uploadFile } from '@/utils/axios.ts'

const queryFormRef = ref(ElForm); // 查询表单
const userFormRef = ref(ElForm); // 用户表单
const uploadRef = ref<UploadInstance>(); // 上传组件

const loading = ref(false); //  加载状态
const removeIds = ref([]); // 删除用户ID集合 用于批量删除
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  title: undefined
});
const total = ref(0); // 数据总数
const pageData = ref([]); // 分页数据
const pagination = ref({
  pageNum: 1,pageSize: 10,total: 0,pageCount: 1
});
const uploadFiles = ref([])
const disabled = ref(false);

// 弹窗对象
const dialog = reactive({
  visible: false,
  type: "user-form",
  width: 800,
  title: "",
});

const imgUrl = ref('')
const imgPath = ref('')
const dialogImageUrl = ref()
const dialogVisible = ref()
const action = ref('/dev/api/v1/common/upload')
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('只能上传jpg格式的图片!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 1) {
    ElMessage.error('图片不能大于1MB!')
    return false
  }
  return true
}
const handleSuccess = (res,file)=>{
  if(res.code === '00000'){
    imgUrl.value = res.data
    imgPath.value = res.data
    formData.pic = imgUrl.value
  }
}
const handleRemove: UploadProps['onRemove'] = (uploadFile) => {
  console.log(uploadFile)
  uploadFile.url = ''
  imgUrl.value = ''
}
const upload = ref<UploadInstance>()
const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = new Date().valueOf();
  upload.value!.handleStart(file)
}

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
// 工具栏配置
const toolbarConfig = {
  toolbarKeys: [
    // 一些常用的菜单 key
    "bold", // 加粗
    "italic", // 斜体
    "through", // 删除线
    "underline", // 下划线
    "bulletedList", // 无序列表
    "numberedList", // 有序列表
    "color", // 文字颜色
    "fontSize", // 字体大小
    "lineHeight", // 行高
    "uploadImage", // 上传图片
    "delIndent", // 缩进
    "indent", // 增进
    "deleteImage", //删除图片
    "divider", // 分割线
    "justifyCenter", // 居中对齐
    "justifyJustify", // 两端对齐
    "justifyLeft", // 左对齐
    "justifyRight", // 右对齐
    "undo", // 撤销
    "redo", // 重做
    "clearStyle", // 清除格式
  ],
}
const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
// 编辑器配置
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    uploadImage: {
      server: action.value,
      // headers: { Authorization: uploadFile.Authorization },
      "tenant-id": "1",
      fieldName: "file",
      customInsert(res, insertFn) {
        if (res.code == 0) {
          insertFn(res.data, null, res.data);
        }
      },
    },
  },
};
// 用户表单数据
const formData = reactive({
  id: undefined,
  title: '',
  content: '',
  pic: '',
});

// 校验规则
const rules = reactive({
  title: [{ required: true, message: "新闻标题不能为空", trigger: "blur" }],
});

/** 查询 */
function handleQuery() {
  getPage(queryParams.pageNum,queryParams.pageSize);
}

function getPage(currentPage:number,pageSize :number){
  pagination.value.pageNum = queryParams.pageNum = currentPage || 1;
  pagination.value.pageSize = queryParams.pageSize = pageSize || 10
  loading.value = true;
  getNewsPage(queryParams)
    .then(({ data }) => {
      pageData.value = data.records;
      total.value = data.total;
      pagination.value.pageNum = data.current
      pagination.value.pageSize = data.size
      pagination.value.total = data.total
      pagination.value.pageCount = data.pages
      queryParams.pageNum = data.current;
      queryParams.pageSize = data.size;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/**
 * 打开弹窗
 *
 * @param type 弹窗类型  用户表单：user-form
 * @param id 用户ID
 */
async function openDialog(type: string, id?: number) {
  dialog.visible = true;
  dialog.type = type;

  if (dialog.type === "user-form") {
    if (id) {
      dialog.title = "修改新闻信息";
      disabled.value = true;
      getNewsForm(id).then(({ data }) => {
        Object.assign(formData, { ...data });
        uploadFiles.value = [{
          url: data.pic
        }]
        imgUrl.value = data.pic;
      });
    } else {
      dialog.title = "新增新闻信息";
    }
  }
}

/**
 * 关闭弹窗
 *
 * @param type 弹窗类型  用户表单：user-form
 */
function closeDialog() {
  dialog.visible = false;
  if (dialog.type === "user-form") {
    userFormRef.value.resetFields();
    userFormRef.value.clearValidate();
    uploadFiles.value = []
    imgUrl.value = ''
    imgPath.value = ''
    formData.id = undefined;
    // formData.status = 1;
  }
}

/** 表单提交 */
const handleSubmit = (() => {
  if (dialog.type === "user-form") {
    userFormRef.value.validate((valid: any) => {
      if (valid) {
        const id = formData.id;
        console.log('==========================',formData);
        loading.value = true;
        if (id) {
          updateNews(formData)
            .then(() => {
              ElMessage.success("修改信息成功");
              closeDialog();
              resetQuery();
            })
            .finally(() => (loading.value = false));
        } else {
          addNews(formData)
            .then(() => {
              ElMessage.success("新增信息成功");
              closeDialog();
              resetQuery();
            })
            .finally(() => (loading.value = false));
        }
      }
    });
  }
});

/** 删除设备 */
function handleDeleteEquipment(id: number) {
  ElMessageBox.confirm("确认删除场地信息?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    deleteNews(id).then(() => {
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

onMounted(() => {
  handleQuery();
});
</script>
.toolbar {
padding: 10px 0;
}
<style scoped>
.footer {
  margin-top: 20px;
}
::v-deep .w-e-text-container {
  height: 420px !important;
}
.w-e-text-container .w-e-scroll {
  height: 500px !important;
  -webkit-overflow-scrolling: touch;
}
</style>
